﻿using System;
using System.Collections.ObjectModel;
using System.Data;
using System.Data.SqlClient;

using Sunyi.Project.WebPoint.DataContract;

namespace Sunyi.Project.WebPoint.DataAccess
{
    public partial class PermissionDao
    {
        public Permission SelectByName(string permissionName)
        {
            Permission permission = null;

            SqlConnection connection = ConnectionProvider.CreateConnection();
            SqlCommand command = connection.CreateCommand();
            command.CommandType = CommandType.StoredProcedure;
            command.CommandText = "procPR_Permission_SelectByName";
            command.Parameters.Add(new SqlParameter("@PermissionName", permissionName));

            try
            {
                connection.Open();

                using (SqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        permission = CreateEntityByReader(reader);
                    }
                }
            }
            finally
            {
                ConnectionProvider.CloseConnection(connection);
            }

            return permission;
        }

        public Collection<Permission> SelectAll()
        {
            Collection<Permission> permissions = new Collection<Permission>();

            SqlConnection connection = ConnectionProvider.CreateConnection();
            SqlCommand command = connection.CreateCommand();
            command.CommandType = CommandType.StoredProcedure;
            command.CommandText = "procPR_Permission_SelectAll";

            try
            {
                connection.Open();

                using (SqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        Permission permission = CreateEntityByReader(reader);
                        permissions.Add(permission);
                    }
                }
            }
            finally
            {
                ConnectionProvider.CloseConnection(connection);
            }

            return permissions;
        }

        public void FillUserRoles(User user)
        {
            string columnName = "UserId";
            string associatedTableName = "PR_User_Role";
            string associatedColumnName = "RoleId";

            DaoHelper.FillEntity<Guid>(user.Roles, user.Id, columnName,associatedTableName,associatedColumnName);
        }
    }
}
